<?php

namespace app\system\controller;

use app\common\base\_Db;
use app\common\controller\CommonController;
use app\common\entity\RequestEntity;
use think\Db;
use app\common\extend\Tools;

class Externalstaff extends CommonController{
    //操作人
    public function GetUserName($id){
        $res = Db::name('staff')
            ->field('nick_name')
            ->where('staff_id ='.$id)
            ->find();
        return $res['nick_name'];
    }
    public function AddStaff(){
        $Phone = new RequestEntity('Phone', '电话', false, 32);
        //手机号校验
        $res_phone = _Db::GetData('external_staff',array('id'=>'uid'),'phone_number = '.$Phone->text);
        if (!empty($res_phone)){
            _Db::Response(2,'手机号已存在');
        }else{
            $Name = new RequestEntity('Name', '姓名', false, 32);
            //$Status = new RequestEntity('Status', '状态', false, 32);
            $Sex = new RequestEntity('Sex', '性别', false, 32);
            $CompanyId = new RequestEntity('CompanyId', '公司id', false, 32);
            $post_creatid = new RequestEntity('CreatId', '操作人', false, 32);
            $ro =file_get_contents('php://input'); //获取json文件
            $reg=json_decode($ro,true); //将json转为PHP数组，供操作
            $PicUrl = Tools::uploads($reg['Img'],'exterstaff');
            if(
            Db::name('external_staff')
                ->insert(
                    [
                        'nick_name'=>$Name->text,
                        //'status'=>$Status->text,
                        'gender'=>$Sex->text,
                        'phone_number'=>$Phone->text,
                        'company_id'=>$CompanyId->text,
                        'pic_url' =>$PicUrl
                    ]
                )
            )
            {
                _Db::log($post_creatid->text,1,'外部员工添加');
                $this->ListStaff();
            }else{
                _Db::Response(0,'添加失败');
            }
        }
    }

    /**
     * 公司列表
     */
    public function SelectCompany(){
        $res = Db::name('external_company')
            ->field([
                'company_id','company_name'
            ])
            ->select();
        return json_encode($res);
    }

    public function ListStaff(){
        $param_page = $get_page = input('Page', 1);
        $param_pagesize =  10;
        $get_keyword = new RequestEntity('search_key', '搜索内容', false, 0);
        $CompanyId = new RequestEntity('CompanyId', '部门id', false, 32);
        $RegistStutas = new RequestEntity('RegistStutas', '绑定状态', false, 32);
        $where = '1=1';
        if(!empty($RegistStutas->text)){
            $where .= ' and s.regist ='.$RegistStutas->text;
        }
        if(!empty($CompanyId->text)){
            $where .= ' and s.company_id ='.$CompanyId->text;
        }
        if(!empty($get_keyword->text)){
            $where .= ' and nick_name  like "%' . $get_keyword->text.'%"'.' or c.company_name  like "%' . $get_keyword->text.'%"';
        }
        $res = Db::name('external_staff s')
            ->field('s.id as Id,s.nick_name as Name, s.gender as Sex, s.phone_number as Phone,s.regist as Regist,s.pic_url as Url, c.company_name as CompanyName,s.oper_id as Operator')
            ->join('external_company c', 's.company_id = c.company_id')
            ->where($where)
            ->limit(($param_page - 1) * $param_pagesize, $param_pagesize)
            ->select();
        foreach ( $res as $key => $value){
            $res[$key]['Url'] = HttpPath .$value ['Url'];
            if($res[$key]['Operator']){//操作者id 转换姓名
                $res[$key]['Operator']=$this->GetUserName($res[$key]['Operator']);
            }
            if ($value['Regist'] == 1){
                $res[$key]['registName'] = '未绑定';
            }elseif ($value['Regist'] == 2){
                $res[$key]['registName'] = '已绑定';
            }
//            elseif ($value['Regist'] == 3){
//                $res[$key]['registName'] = '已审核';
//            }elseif ($value['Regist'] == 4){
//                $res[$key]['registName'] = '已驳回';
//            }
            $res[$key]['Order'] = $key + 1;
        };
        $int_total_count = count(Db::name('external_staff s')
            ->join('external_company c', 's.company_id = c.company_id')
            ->where($where)
            ->select());
        $data['tableData']=$res;
        $data['TotalCount'] = $int_total_count;
        $data['Page'] = (int)$param_page;
        $data['PageSize'] = (int)$param_pagesize;
        _Db::ResponseJson($data);
    }
    public function ItemStaff(){
        $Id = new RequestEntity('Id', 'Id', false, 32);
        $res = Db::name('external_staff')
            ->field([
                'e.id'          =>'Id',
                'e.nick_name'   =>'Name',
                'e.gender'      =>'Sex',
                'e.phone_number'=>'Phone',
                'e.pic_url'     =>'Url',
                'e.company_id'  =>'CompanyId',
                'd.company_name'=>'CompanyName'
            ])
            ->alias('e')
            ->join('external_company d','e.company_id = d.company_id','LEFT')
            ->where('id ='.$Id->text)
            ->find();
        $res['Url'] = HttpPath.$res['Url'];
        _Db::ResponseJson($res);
    }
    public function ListCompany(){
        $res = Db::name('external_company')
            ->field([
                'company_id',
                'company_name',
            ])
            ->select();
        return json_encode($res);
    }
    public function ModifyStaff(){
        $Id = new RequestEntity('Id', 'Id', false, 32);
        $Phone = new RequestEntity('Phone', 'Phone', false, 32);
        //手机号校验
        $res_phone = _Db::GetData('external_staff',array('id'=>'uid'),'id !='.$Id->text.' and phone_number = '.$Phone->text);
        if (!empty($res_phone)){
            _Db::Response(2,'手机号已存在');
        }else{
            $Name = new RequestEntity('Name', 'Name', false, 32);
            $Sex = new RequestEntity('Sex', 'Sex', false, 32);
            $CreatId = new RequestEntity('CreatId', 'CreatId', false, 32);
            $CompanyId= new RequestEntity('CompanyId', 'CompanyId', false, 32);
            $ro =file_get_contents('php://input'); //获取json文件
            $reg=json_decode($ro,true); //将json转为PHP数组，供操作
            $update = [
                'oper_date' => date('Y-m-d H:i:s',time()),
                'oper_id' => $CreatId->text
            ];
            Db::name('external_staff')->where('id ='.$Id->text)->update($update);
            $field = array(
                'nick_name'=>$Name->text,
                'gender'=>$Sex->text,
                'phone_number'=>$Phone->text,
                'company_id'=>$CompanyId->text,
            );
            if (!empty($reg['Img'])){
                $PicUrl = Tools::uploads($reg['Img'],'exterstaff');
                $field['pic_url'] = $PicUrl;
            }
            if(Db::name('external_staff')->where('id ='.$Id->text)->update($field)){
                _Db::log($CreatId->text,3,'外部员工修改');
                $this->Item($Id->text);
            }else{
                _Db::Response(0,'修改失败');
            }
        }
    }
    public function Item($id){
        $res = Db::name('external_staff')
            ->field([
                'e.id'          =>'Id',
                'e.nick_name'   =>'Name',
                'e.gender'      =>'Sex',
                'e.phone_number'=>'Phone',
                'e.pic_url'     =>'Url',
                'e.company_id'  =>'CompanyId',
                'e.regist'      => 'Regist',
                'd.company_name'=>'CompanyName'
            ])
            ->alias('e')
            ->join('external_company d','e.company_id = d.company_id','LEFT')
            ->where('id ='.$id)
            ->find();
        if ($res['Regist'] == 1){
            $res['registName'] = '未认证';
        }elseif ($res['Regist'] == 2){
            $res['registName'] = '已认证';
        }elseif ($res['Regist'] == 3){
            $res['registName'] = '已审核';
        }elseif ($res['Regist'] == 4){
            $res['registName'] = '已驳回';
        }
        $res['Url'] = HttpPath.$res['Url'];
        _Db::ResponseJson($res);
    }

    public function RemoveStaff(){
        $Id = new RequestEntity('Id', 'Id', false, 32);
        $post_creatid = new RequestEntity('CreatId', 'CreatId', false, 32);
        $res = _Db::GetData('external_staff','openid,regist','id = '.$Id->text);
        if(
            Db::name('external_staff')->where('id ='.$Id->text)->delete()
        ){
            //外部员工已审核，删除该员工时删除用户表对应数据
            if ($res['openid']!=''&&$res['regist']==3){
                Db::name('user')->where('openid ='.$res['openid'])->delete();
            }
            _Db::log($post_creatid->text,2,'外部员工删除');
            $this->ListStaff();
        }else{
            _Db::Response(0,'删除失败');
        }
    }
    //审核
    public function SwitchModity(){
        //获取请求参数
        $request_data = [
            $post_itemid = new RequestEntity('Id', 'ID', true, 10),
            $post_value = new RequestEntity('Value', '值', true, 10),
            $post_creatid = new RequestEntity('CreatId','操作人Id', false, 30),
        ];
        //表单内容验证
        _Db::Validates($request_data);
        //设置条件
        $param_where = [
            'id' => $post_itemid->text,
        ];
        $res = _Db::GetData('external_staff','openid',$param_where);
        if ($post_value->text == 3){
            $type = 7;
            $content = '人员审核';
            $param_field = [
                'regist'    => 3,
                'oper_id'   => $post_creatid->text,
                'oper_date' => date("Y-m-d H:i:s",time()),
            ];
            if (!empty($res)){
                Db::name('user')->where('openid ="'.$res['openid'].'"')->update(['iden'=>3]);
            }
        }elseif ($post_value->text == 4){
            $type = 8;
            $content = '审核驳回';
            $param_field = [
                'regist'    => 4,
                'oper_id'   => $post_creatid->text,
                'oper_date' => date("Y-m-d H:i:s",time()),
            ];
            if (!empty($res)){
                Db::name('user')->where('openid ="'.$res['openid'].'"')->update(['iden'=>1]);
            }
        }
        $result = Db::table('external_staff')
            ->where($param_where)
            ->update($param_field);
        if ($result){
            _Db::log($post_creatid->text,$type,$content);
            $this->Item($post_itemid->text);
        }
    }
}